import { Emitter } from '../Emitter';
import { HEALTH_CARD_TYPE, genderEnum } from './constant';
import dayjs from 'dayjs';
import { reportHisData } from '@/apis/healthCard';

// 提示
const _toast = (title, complete) => {
  uni.showToast({
    title,
    icon: 'none',
    mask: true,
    duration: 1500,
    complete: () => {
      // 延迟触发
      setTimeout(() => {
        complete && complete();
      }, 1500);
    },
  });
};

// 加载
const _showLoading = (title = '加载中') => {
  uni.showToast({
    title,
    duration: 1000 * 60 * 60 * 24,
    icon: 'loading',
    mask: true,
  });
};

const _hideLoading = delayTime => {
  // 延迟关闭
  if (delayTime && typeof delayTime === 'number') {
    setTimeout(() => {
      uni.hideToast();
    }, delayTime);
  } else {
    uni.hideToast();
  }
};

// 日志
const _log = (...args) => {
  console.log(...args);
};

class HealthCardUtil {
  // 更新参数
  patientId = '';
  // 绑定参数
  patientInfo = '';
  // 授权验证
  scene = '';
  formPath = '';
  verifyOrderId = '';
  // 回调匹配的路由
  matchRoute = '';
  // 临时存储健康卡信息
  healthCardInfo = null;
  constructor() {
    this.emitter = new Emitter();
    this.showLoad = _showLoading;
    this.hideLoad = _hideLoading;
    this.toast = _toast;
    this.log = _log;
  }
  create() {
    this.recordFormPath();
    uni.navigateTo({
      url: `/patientPages/healthCard/auth/index?type=${HEALTH_CARD_TYPE.CREATE}`,
    });
  }
  update(patientId) {
    this.recordFormPath();
    this.patientId = patientId;
    uni.navigateTo({
      url: `/patientPages/healthCard/auth/index?type=${HEALTH_CARD_TYPE.UPDATE}`,
    });
  }
  // 验证
  async verify({ scene, patientInfo, success, fail }) {
    this.showLoad('跳转中');
    const { healthCardId } = patientInfo;
    // 非电子健康卡直接跳过
    if (!healthCardId) {
      success && success();
      return;
    }
    this.patientInfo = patientInfo;
    this.recordFormPath();
    // 注册监听事件
    this.onVerifySuccess(success);
    this.onVerifyFail(fail);
    this.scene = scene;

    // 进行上报
    await this.eventData({
      qrCodeText: healthCardId,
      scene,
    });
    setTimeout(() => {
      this.hideLoad();
      uni.navigateTo({
        url: `/patientPages/healthCard/auth/index?type=${HEALTH_CARD_TYPE.SEARCH_VERIFY}`,
      });
    }, 500);
  }
  // 注册验证成功事件
  onVerifySuccess(success) {
    _log('【onVerifySuccess】', success);
    // 防止重复注册
    this.emitter.remove('verifySuccess');
    this.emitter.once('verifySuccess', e => {
      success && success(e);
    });
  }
  emitVerifySuccess(e) {
    this.emitter.emit('verifySuccess', e);
  }
  // 注册验证失败事件
  onVerifyFail(fail) {
    _log('【onVerifyFail】', fail);
    // 防止重复注册
    this.emitter.remove('verifyFail');
    this.emitter.once('verifyFail', e => {
      fail && fail(e);
    });
  }
  emitVerifyFail(e) {
    this.emitter.emit('verifyFail', e);
  }
  // 验证成功后
  verifySuccess() {
    this.toast('验证通过', () => {
      // 返回来源路由
      this.goBack(this.formPath, () => {
        // 延迟触发
        setTimeout(() => {
          this.emitVerifySuccess();
        }, 200);
      });
    });
  }
  // 验证失败后
  verifyFail() {
    this.toast('验证失败', () => {
      this.goBack(this.formPath, () => {
        // 延迟触发
        setTimeout(() => {
          this.emitVerifyFail();
        }, 200);
      });
    });
  }
  // 记录来源路由
  recordFormPath() {
    // 来源路由
    const curPages = getCurrentPages();

    const curPage = curPages[curPages.length - 1];
    this.formPath = curPage.route;
    console.log('【formPath】', this.formPath);
  }
  // 匹配重定向的路径，返回到对应的页面
  goBack(route = this.formPath, callback) {
    // 返回到就诊人列表页
    const curPages = getCurrentPages();
    const pageLen = curPages.length;

    let delta = 1;
    while (delta <= pageLen - 1) {
      if (curPages[pageLen - delta - 1].route === route) {
        this.hideLoad();
        uni.navigateBack({
          delta: delta,
          complete: () => {
            if (callback) {
              callback();
            }
          },
        });
        break;
      }
      delta++;
    }
  }
  // 记录verifyOrderId，用于校验
  recordVerifyOrderId(verifyOrderId) {
    this.verifyOrderId = verifyOrderId;
  }
  // 健康卡信息转患者信息
  transferInfoByHealthCard(healthCardInfo) {
    try {
      const {
        name,
        birthday,
        idType,
        idNumber,
        gender,
        address,
        healthCardId,
        patid,
        phone1,
        nation,
        relation,
        relationship,
        isSelf,
      } = healthCardInfo;
      const genderInfo = genderEnum.find(it => it.name === gender);

      let addressObj = null,
        provinceInfo,
        cityInfo,
        districtInfo;
      // 验证地址是否符合要求
      const verifyResult = this.verifyAddress(address);
      if (verifyResult) {
        addressObj = JSON.parse(address);
        provinceInfo = addressObj.city[0];
        cityInfo = addressObj.city[1];
        districtInfo = addressObj.city[2];
      }

      const _birthday =
        birthday || idNumber.substr(6, 8).replace(/(.{4})(.{2})/, '$1-$2-');
      const _sex = parseInt(idNumber.substr(16, 1)) % 2 == 1 ? 1 : 2;
      return {
        name,
        birthday: new Date(_birthday).getTime(),
        certType: Number(idType),
        certId: idNumber,
        sex: genderInfo ? genderInfo.value : _sex,
        address: addressObj
          ? {
              province: provinceInfo?.text,
              provinceCode: provinceInfo?.value,
              city: cityInfo?.text,
              cityCode: cityInfo?.value,
              district: districtInfo?.text,
              districtCode: districtInfo?.value,
              address: addressObj.address,
            }
          : null,
        nationality: '中国',
        nationalityCode: 'ZG',
        healthCardId,
        patid,
        phone: phone1,
        nation: nation || '汉族',
        relation: relation || relationship || isSelf ? '0' : '',
      };
    } catch (err) {
      this.toast('健康卡数据异常，请解绑后重新添加');
      throw new Error('健康卡数据异常，请解绑后重新添加');
    }
  }
  // 患者信息转健康卡信息
  transferInfoByPatientInfo(patientInfo) {
    const {
      name,
      birthday,
      certType,
      certId,
      sex,
      phone,
      currentAddress,
      relation,
    } = patientInfo;

    let city = [];
    let address = '';
    if (currentAddress && currentAddress.province) {
      city = [
        { text: currentAddress.province, value: currentAddress.provinceCode },
        { text: currentAddress.city, value: currentAddress.cityCode },
        { text: currentAddress.district, value: currentAddress.districtCode },
      ];
      address = currentAddress.address;
    } else {
      // 默认地址
      city = [
        { text: '四川省', value: '510000' },
        { text: '泸州市', value: '510500' },
        { text: '江阳区', value: '510502' },
      ];
    }
    return {
      ...patientInfo,
      name,
      birthday: dayjs(new Date(birthday)).format('YYYY-MM-DD'),
      idType: certType >= 10 ? String(certType) : '0' + String(certType),
      idNumber: certId,
      gender: sex,
      phone,
      city,
      address,
      relation,
    };
  }

  // 用卡证件 10	就诊卡、11	电子健康卡
  getCardType(healthCardId) {
    return healthCardId ? '11' : '10';
  }
  // 根据名称匹配上报场景
  getScene(title) {
    const scene = {
      change_patient: '0101087', // 基本信息
      unbind: '01010871', // 解绑
      medical_record: '010108', // 就医记录,
      check_report: '0101081', // 检查报告
      inspection_report: '0101082', // 检验报告
      digital_image: '02010913', // 数字影像
      queuing_up: '0101021', // 排队叫号
      pay: '010105', // 缴费
      outpatient_pay: '0101051', // 门诊缴费
      outpatient_record: '0101052', // 门诊记录
      appointment_register: '0101011', // 预约挂号
      today_register: '0101012', // 当日挂号
    };
    return scene[title];
  }
  // 数据上报
  eventData(param) {
    return new Promise(resolve => {
      _log('reportHisData 参数】', param);
      const { scene, qrCodeText, department } = param;

      if (!qrCodeText) {
        resolve();
        return;
      }
      const params = {
        qrCodeText,
        scene,
        cardType: '11',
        cardChannel: '0402',
        time: dayjs().format('YYYY-MM-DD'),
      };
      if (department) {
        params.department = department;
        params.cardCostTypes = '0100';
      }
      reportHisData(params)
        .then(res => {
          _log('reportHisData 结果】', res);
          resolve(res);
        })
        .catch(err => {
          _log('reportHisData 结果】', err);
          resolve();
        });
    });
  }
  /**
   * 手机号脱敏处理
   * @param {string} phone - 手机号字符串
   * @returns {string} 脱敏后的手机号
   */
  maskPhone(phone) {
    if (!phone) return '--';
    // 去除非数字字符
    const cleanPhone = phone.replace(/\D/g, '');
    // 验证是否为11位数字
    if (!/^\d{11}$/.test(cleanPhone)) {
      return phone; // 非标准手机号不做处理
    }
    // 格式化：（中间4位用*替换）
    return cleanPhone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
  }

  /**
   * 身份证号脱敏处理
   * @param {string} idCard - 身份证号字符串
   * @returns {string} 脱敏后的身份证号
   */
  maskIdCard(idCard) {
    if (!idCard) return '--';
    // 去除非数字和字母字符（支持15位和18位身份证号）
    const cleanIdCard = idCard.replace(/[^\dXx]/g, '').toUpperCase();
    // 验证15位或18位身份证号
    const isValid15 = /^\d{15}$/.test(cleanIdCard);
    const isValid18 = /^\d{17}[\dX]$/.test(cleanIdCard);
    if (!isValid15 && !isValid18) {
      return idCard; // 非标准身份证号不做处理
    }

    // 格式化：中间10位用*替换
    if (isValid15) {
      return cleanIdCard.replace(/(\d{1})(\d{10})(\d{4})/, '$1**********$3');
    } else {
      return cleanIdCard.replace(
        /^(\d{4})(\d{10})(\d{3}[\dX])$/,
        '$1**********$3',
      );
    }
  }
  // 验证地址是否正确
  verifyAddress(address) {
    if (!address) return false;
    try {
      const obj = JSON.parse(address);
      // 验证数据结构
      if (obj.city && obj.address) {
        return true;
      } else {
        return false;
      }
    } catch (error) {
      // 数据格式不正确
      return false;
    }
  }
}
export default new HealthCardUtil();
